package com.binyouwei.udp_lib.factory;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.binyouwei.udp_lib.Configure;
import com.binyouwei.udp_lib.ReceiveMessageInterface;
import com.binyouwei.udp_lib.SingleThreads;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * @author 宾有为
 * @date 2024/6/11 20:04
 * @link https://blog.csdn.net/baidu_41616022?type=blog
 * @describe：
 **/
public class UnicastFactory implements UdpFactory {
    final String TAG = getClass().getSimpleName();
    final int port = 8888;
    boolean isFinish = false;
    @Override
    public void initUdp() {
        isFinish = true;
    }

    @Override
    public void destroyUdp() {
        isFinish = false;
    }

    @Override
    public void sendMessage(@NonNull String ip, @NonNull String message) {
        SingleThreads.getInstance().execute(() -> {
            try {
                DatagramSocket socket = new DatagramSocket();
                // 设置端口复用
                byte[] sendData = message.getBytes();
                // 创建回复的数据包
                InetAddress inetAddress = InetAddress.getByName(ip);
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, inetAddress, port);
                // 发送消息到目标IP
                socket.send(sendPacket);
                socket.close();
                Log.e(TAG, "发送广播成功，message：" + message);
            } catch (IOException e) {
                Log.e(TAG, "发送广播失败，message：" + e.getMessage());
                throw new RuntimeException(e);
            }
        });
    }

    @Override
    public void onReceiveMessageListener(@NonNull String ip, @NonNull ReceiveMessageInterface receiveMessage) {
        SingleThreads.getInstance().execute(() -> {
            try {
                byte[] receiveData = new byte[1024];
                DatagramSocket socket = new DatagramSocket(port);
                // 创建DatagramPacket准备接收数据
                while (isFinish) {
                    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                    // 接收数据包
                    socket.receive(receivePacket);
                    // 获取数据和发送方地址
                    String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
                    Log.e(TAG, "广播收到一条消息，message：" + message);
                    receiveMessage.onReceiveMessageListener(message);
                }
                socket.close();
            } catch (IOException e) {
                Log.e(TAG, "广播接收消息失败，message：" + e.getMessage());
                throw new RuntimeException(e);
            }
        });
    }
}
